import util from "@/libs/util";
import { fetchFile } from "@/libs/commonApi";
import { modal } from "@/libs/commonApi/operation";
import { dateRangeValide } from "@/libs/validator/function";
import {
  evaluateMyRepair,
  getCBaseInfoListByCliqueId
} from "@/api/operation";
import iview from 'view-design';

export const preview = {
  methods: {
    filePreview(item,params,tableName) {
      if (item && item.url) {
        item.downloading = true
        // this.tableData
        if(tableName) {
          this.$set(this[tableName],params.index,params.row)
        }else{
          this.$set(this.tableData,params.index,params.row)
        }
        
        if(sliceString(item.attachmentName.split(".")[1])){
          fetchFile(item.url).then(blob => {
            item.downloading = false
            if(tableName) {
              this.$set(this[tableName],params.index,params.row)
            }else{
              this.$set(this.tableData,params.index,params.row)
            }
            
            let url = window.URL.createObjectURL(blob);
            modal(item,url,true)
          });
        }else{
          fetchFile(item.url).then(blob => {
            item.downloading = false
            this.$set(this.tableData,params.index,params.row)
            util.download(blob, item.attachmentName);
          });
        }
        
      }
    }
  }
}

const sliceString = (extension) => {
  return (
    extension === "jpg" ||
    extension === "jpeg" ||
    extension === "gif" ||
    extension === "png"
  );
}

export const evaluateChange = {
  methods: { 
    evaluateChange(params, val) {
      const row = params.row;
      row.degreeSatisfaction = val;
      console.log(val,"11")
      this.$Modal.confirm({
        title: "温馨提示",
        content: "确认评价任务名称为"+ params.row.taskName +"的工单？",
        onOk: () => {
          this.$set(this.tableData, params.index, params.row);
          const obj = {
            workOrderId: row.workOrderId,
            sWorkEvaluate: {
              arrivalSpeed: val,
              faultEfficiency: val,
              processingResults: val,
              responseSpeed: val,
              serviceAttitude: val
            }
          };
          evaluateMyRepair(obj)
            .then(res => {
              if (res.code === 200) {
                this.formQuery();
              } else {
                this.$Message.error("评价失败，请稍后再试");
              }
            })
            .catch(err => {
              this.$Message.error("网络错误，请稍后再试");
            });
        },
        onCancel: () => {
          params.row.degreeSatisfaction = 0
          this.$set(this.tableData,params.index,params.row)
        }
      });
     
    
    
    }
  }
}

export const exportFile = {
  methods: {
    exportFile(data,url,name) {
      if (data === 3) {
        this.$Modal.confirm({
          title: "温馨提示",
          content: "确认导出为excel格式？",
          onOk: () => {
            fetch(
              url,
              {
                method: "POST",
                headers: {
                  "Content-Type": "application/json",
                  Authorization: this.$cookie.get("access_token")
                },
                body: JSON.stringify({ ...this.listQuery })
              }
            )
              .then(res => res.blob())
              .then(blob => {
                util.download(blob, name);
                iview.Message.success("下载成功")
              });
          }
        });
      }
    }
  }
}
export const queryAndReset = {
  data() {
    return {
      formKey: 345
    }
  },
  methods: {
    // 查询
    formQuery() {
      const keys = [["startDate","endDate"],["bgnTime","endTime"],["startTime","endTime"],["bgnDate","endDate"]]
    //   Object.keys(this.formItem).forEach(item => {
    //    this.listQuery[item] = this.formItem[item];
    //  });
     let days = 0
     for(const key in this.formItem) {
       if(this.formItem[key]===0) {
        this.listQuery[key] = null
       }else{

       this.listQuery[key] = this.formItem[key];
      }
       keys.some(v=>{
         if(v[0]===key) {
          days = dateRangeValide(this.formItem[v[0]],this.formItem[v[1]],30)
          return true
         }
       })
     }
     
    //  if(days==='1') return this.$Message.warning("开始/起始时间大于结束/截止时间")
    //  if(days==='2') return this.$Message.warning("由于数据量大时间范围不能大于30天")
    //  if(days==='3') return this.$Message.warning("请输入开始/起始时间、结束/截止时间")
    //  if(days==='4') return this.$Message.warning("结束/截止时间不能大于今天")

     this.tablePageData = {
       pageNum: 1,
       pageSize: this.listQuery.pageSize
     }
     // this.initTable();
   },

   //重置
   formReset() {
     // 重置时会出现个别数据不更新的情况，使用key解决
     this.formKey+=1;
    const keys = [["startDate","endDate"],["bgnTime","endTime"],["startTime","endTime"],["bgnDate","endDate"]]
     Object.keys(this.formItem).forEach(item => {
       if((this.reserveField || []).indexOf(item) == -1){
        this.formItem[item] = "";
        this.listQuery[item] = "";
       }
       if(['areaNo','orgNo','delayTimes'].includes(item)) {
        this.formItem[item] = null
       }
       if(this.custInfo.custId&&item==='siteId') {
        this.formItem[item] = this.$options.data().formItem[item]
       }
       keys.some(v=>{
         if(v[0]===item) {
          this.formItem[v[0]] = this.$options.data().formItem[v[0]]
          this.formItem[v[1]] = this.$options.data().formItem[v[1]]
          return true
         }
       })
     });
     this.tablePageData.pageNum = 1
     // 重新获取客户列表
     this.getCBaseInfoListByCliqueId();
     // 重新拉取列表
     this.initTable();
   },
   areaChange(val) {
      //console.log(val,'----')
      this.formItem.custNo = ""
      this.dicData.custName = []
      this.getCBaseInfoListByCliqueId(val.id)
    },
    /**
     * 获取当前集团下用户
     */
    getCBaseInfoListByCliqueId(areaNo = null) {
      getCBaseInfoListByCliqueId({ areaNo }).then(
      // getCBaseInfoListByCliqueId({ areaNo, customerTypes: ["06"] }).then(
        res => {
          if (res.code === 200 && res.result) {
            this.$set(this.dicData, "custName", res.result);
          } else {
            this.dicData.custName = [];
          }
        }
      );
    },
  }
}
export const checkFile={
  methods:{
    checkFile(url,text){
      const msg = this.$Message.loading({
                    content: "加载中...",
                    duration: 0
                });
      fetchFile(url).then(blob=>{
        setTimeout(msg,0);
       
        if(text=='img'){
            let urls = window.URL.createObjectURL(blob);
            modal(null,urls,true)
        }else{
             util.download(blob, text);
        }
        // window.open(url);
      })
    }
  }
}
export const stepModel={
  methods:{
    onlySelectedRow(val, index) {
        this.atPresentClickRow = val;
        this.stepModalShow = true
    },
    stepModalShowCancel() {
        this.stepModalShow = false
    },
  }
}
